
import wx

def boundingBox(polygon):
    xs = [x for x, y in polygon]
    ys = [y for x, y in polygon]
    return (max(min(xs) - 4, 0), max(min(ys) - 4, 0), 
            max(xs) + 4, max(ys) + 4)

def generateMask(polygon, x1, y1, x2, y2, background=(0, 0, 0)):
    """Generates the mask which can be rendered over the rectangle x1,y1, x2,y2.
    """
    
    # make alpha mask
    bmp = wx.EmptyBitmap(x2 - x1, y2 - y1, 24)
    dc = wx.MemoryDC(bmp)
    dc.SetBackground(wx.Brush(wx.Colour(*background)))
    dc.Clear()
    viewPoly = [(x - x1, y - y1) for x, y in polygon]
    for invWidth in range(8):
        b = 256 * (invWidth + 1) / 8 - 1
        dc.SetPen(wx.Pen(wx.Colour(b, b, b), width = 8 - invWidth))
        dc.DrawLines(viewPoly + viewPoly[:1])
    dc.SetBrush(wx.Brush(wx.Colour(255, 255, 255)))
    dc.DrawPolygon(viewPoly)
    return bmp.ConvertToImage()


def applyMask(image, mask):
    # convert to imageData
    image.SetAlphaData(mask.GetData()[::3])
    return wx.BitmapFromImage(image)

